import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Route, Link } from 'dva/router';
import {
  Row, Col, Card, Form, Input, Select, Icon,
  Button, Table, List, message, Checkbox, Divider
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { routerRedux } from 'dva/router';
import styles from './RoleManagement.less';
import querystring from 'querystring';
/*
 角色管理权限配置界面
*/

const { Option, OptGroup } = Select;

@connect(({ role }) => ({
  role,
}))
export default class RoleAuthorization extends PureComponent {
  state = {
    id: '',
    selectedRowId: [],
    selectedRowKeys: [],
    ItemId: {},
    resourcesListId: {},
    selectedResourceKeys: [],
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    // console.log(`this.props.location`);
    const params = querystring.parse(location.search.slice(1));
    this.setState({
      id: params.id
    })
    dispatch({
      type: 'role/getAllMenusByRoleId',
      payload: {
        roleId: params.id
      },
      callback: () => {
        const { role: { resourcesList } } = this.props;
        const { roleResource, roleMenuIdList } = resourcesList;

        // console.log("resourcesList=", resourcesList);
        // console.log("roleResource=", roleResource);

        let selectedResourceKeys = [];

        roleResource.map((item) => {
          selectedResourceKeys.push(item.id);
        });

        this.setState({
          resourcesListId: resourcesList,
          selectedResourceKeys,
          selectedRowId: roleMenuIdList,
        });
        // console.log("resourcesList=", resourcesList);
        // console.log("roleMenuIdList=", roleMenuIdList);
        // console.log("selectedRowId=", this.state.selectedRowId);
      }
    });
  }

  addSelection = (key) => {
    const selectedRowKeys = [...this.state.selectedRowKeys];

    if (selectedRowKeys.indexOf(key) == -1) {
      selectedRowKeys.push(key);
    }
    this.setState({
      selectedRowKeys,
    });
  }

  addResourceSelection = (key) => {

    const selectedResourceKeys = [...this.state.selectedResourceKeys];

    if (selectedResourceKeys.indexOf(key) == -1) {
      selectedResourceKeys.push(key);
    }
    this.setState({
      selectedResourceKeys,
    });
  }

  handleUpdateAllRoleId = () => {
    const { dispatch } = this.props;
    let hash = [];
    let arr = [];
    const selectedRowId = [...this.state.selectedRowId]
    // console.log("111111111111111111",this.state.selectedRowId)
    for (let i = 0; i < selectedRowId.length; i++) {
      hash[selectedRowId[i]] != null;
      if (!hash[selectedRowId[i]]) {
        arr.push(selectedRowId[i]);
        hash[selectedRowId[i]] = true;
      }
    }
    // console.log("arrAQQAAQQAAQQAAQAQAQA",arr)
    dispatch({
      type: 'role/updateResourceId',
      payload: {
        id: this.state.id,
        menuIdList: arr,
        resourceIdList: this.state.selectedResourceKeys
      },
      callback: () => {
        const { role: { roleResult } } = this.props;
        if (roleResult.code == 200) {
          message.success("提交成功")
          dispatch(routerRedux.push('/system/role-management'));
        } else {
          message.error(roleResult.message)
        }
      }
    })
    // dispatch({
    //   type: 'role/updateAllMenusByRoleId',
    //   payload: {
    //     id: this.state.id,
    //     menuIdList: arr,
    //     resourceIdList: this.state.selectedResourceKeys
    //   },
    // });
  }

  columns = [{
    title: '角色菜单',
    dataIndex: 'name',
    key: 'name',
    width: '30%'
  }, {
    title: '角色权限',
    key: 'id',
    dataIndex: 'id',
    render: (text, item) => {
      return (
        <div>
          {
            item.resourceList.map((resource) => {
              const defaultChecked = this.state.selectedResourceKeys.indexOf(resource.id) > -1;
              // console.log("ewrwrwr",resource)
              return (
                // <Checkbox.Group style={{ width: '100%' }} >
                <Checkbox
                  key={resource.id}
                  checked={defaultChecked}
                  onChange={(e) => {
                    // console.log("onChange=",e);
                    const selectedResourceKeys = [...this.state.selectedResourceKeys];
                    const selectedRowId = [...this.state.selectedRowId];
                    // const indexId = selectedRowId.indexOf(item.id);
                    const index = selectedResourceKeys.indexOf(resource.id);
                    if (e.target.checked) {
                      // console.log("selectedRowId=",selectedRowId);
                      // console.log("selectedResourceKeys222=",selectedResourceKeys);
                      if (index == -1) {
                        selectedRowId.push(item.id);
                        selectedResourceKeys.push(resource.id);
                      }

                    } else {
                      if (index != -1) {
                        // selectedRowId.splice(indexId,1);
                        selectedResourceKeys.splice(index, 1);
                        // console.log("selectedResourceKeys=",selectedResourceKeys);
                      }
                    }
                    this.setState({
                      selectedRowId,
                      selectedResourceKeys,
                    });
                    // console.log("selectedRowId2131313131313",selectedRowId)
                    // console.log("selectedResourceKeyswwwwwww",selectedResourceKeys)
                  }
                  }>{resource.name}

                </Checkbox>
                // </Checkbox.Group>
              );
            })
          }
        </div>
      );
    }
    // },{
    //   title: '操作',
    //   dataIndex: 'name',
    //   key: 'name',
    //   width: '20%',
    //   render: (text, record) => (
    //     //
    //     <Fragment>
    //         <Link to={`/channel/channel-details?id=${record.id}&state=1`}>全选</Link>
    //         {/* <Divider type="vertical" />
    //         {record.state == '0' && record.verifyState == '1' ? <a onClick={() => this.handleSetState(record)}>打开</a> : null}
    //         {record.state == '1' ? <a onClick={() => this.handleSetState(record)}>关闭</a> : null} */}
    //     </Fragment>
    // )
  },
  ];

  render() {
    const { role: { resourcesList, roleLoading, roleResourceLoading } } = this.props;
    const { allResource } = resourcesList;
    const { selectedRowKeys } = this.state;

    return (
      <PageHeaderLayout title="权限配置">

        <Card
          bordered={false} >
          {/* {JSON.stringify(resourcesList)} */}
          <Table
            bordered={false}
            pagination={false}
            dataSource={allResource}
            columns={this.columns}
            loading={roleLoading}
            rowKey="id"
            defaultExpandAllRows={true}
          >
          </Table>
          <div className={styles.tableListOperator}>
            <Button
              style={{ marginTop: 30 }}
              type="primary"
              onClick={() => this.handleUpdateAllRoleId()}
              loading={roleResourceLoading}>
              提交
            </Button>
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}